package com.zhs.gccs.view.taskMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.MimeTypeMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.annimon.stream.Stream;
import com.wwren.picture.lib.PictureSelector;
import com.wwren.picture.lib.entity.LocalMedia;
import com.zhs.gccs.BuildConfig;
import com.zhs.gccs.R;
import com.zhs.gccs.adapter.GccsTakeImageAdapter;
import com.zhs.gccs.model.CaData;
import com.zhs.gccs.model.CaFile;
import com.zhs.gccs.model.SmTask;
import com.zhs.gccs.model.StatisticsDict;
import com.zhs.gccs.model.TaskProject;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.FileUtils;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.view.BaseView;
import com.zhs.gccs.widget.selectImg.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//工程措施抽检
public class GccjTakeImageView extends BaseView implements View.OnClickListener , GccsTakeImageAdapter.OperationListener{
    private RecyclerView recycler_view_pics;//
    private GccsTakeImageAdapter photoAdapter;
    private List<CaFile> photos;
    private Activity activity;
    TaskProject taskProject;
    SmTask smTask;
    StatisticsDict caType;
    StatisticsDict currentLevel;
    private CaData data;//表单数据
    ///////////////////////////////////////


    public List<CaFile> getPhotos() {
        return photos;
    }

    public GccjTakeImageView(@NonNull Context context) {
        super(context);
    }

    public GccjTakeImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public GccjTakeImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_view_take_image, this, true);
//        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomerLogo);
//        String title = typedArray.getString(R.styleable.CustomerInfoItem_preText);
//        typedArray.recycle();
        recycler_view_pics = view.findViewById(R.id.recycler_view_pics);
        recycler_view_pics.setLayoutManager(new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.VERTICAL));
        photos = new ArrayList<>();
        CaFile image = new CaFile();
        image.setImgType(CaFile.type_image);
        image.setPlaceholder(true);
        photos.add(image);
        photoAdapter = new GccsTakeImageAdapter(context,photos);
        recycler_view_pics.setAdapter(photoAdapter);
        photoAdapter.setOperationListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    //编辑模式
    public void loadData(Activity activity,
                         TaskProject taskProject,
                         SmTask smTask,
                         StatisticsDict levelOne,
                         StatisticsDict currentLevel,
                         CaData data,
                         List<CaFile> files,
                         String type ) {
        this.activity = activity;
        this.taskProject = taskProject;
        this.smTask = smTask;
        this.caType = levelOne;
        this.currentLevel = currentLevel;
        this.data = data;
        photos.clear();
        if(files!=null&&files.size()>0){
            Stream.of(files).forEach(item->{
//                CaFile image = new CaFile();
                item.setImgType(type);
                item.setPlaceholder(false);
//                image.setFileId(item.getId());
                photos.add(item);
            });
            CaFile image = new CaFile();
            image.setImgType(type);
            image.setPlaceholder(true);
            photos.add(image);
        }else {
            CaFile image = new CaFile();
            image.setImgType(type);
            image.setPlaceholder(true);
            photos.add(image);
        }
        photoAdapter.notifyDataSetChanged();
    }

    //只读模式
    public void loadDataView(Activity activity,
                             List<CaFile> files,
                             String type) {
        this.activity = activity;
        photos.clear();
        if(files!=null&&files.size()>0){
            Stream.of(files).forEach(item->{
//                CaFile image = new CaFile();
                item.setImgType(type);
                item.setPlaceholder(false);
//                image.setFileId(item.getId());
                item.setVideoThumb(JSON.toJSONString(item.getThumb()));//网络地址
                item.setEditable(false);
                photos.add(item);
            });
        }
        photoAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemPreview(int position, CaFile image) {
        if(CaFile.type_image.equals(image.getImgType())){
            List<LocalMedia> selectList = new ArrayList<>();
            for (int i = 0; i < photos.size(); i++) {
                CaFile imageBean = photos.get(i);
                if (imageBean.isPlaceholder()) {
                    continue;
                }
                String url = imageBean.getLocalPath();
                if(TextUtils.isEmpty(url)){
                    url = BuildConfig.BASEFILEURL+imageBean.getFileId()
                            +"?token="+ SharedPrefHelper.getInstance().getToken();
                }
                LocalMedia media = new LocalMedia();
                media.setPath(url);
                media.setRealPath(url);
                media.setCutPath(url);
                media.setAndroidQToPath(url);
                media.setCompressPath(url);
                media.setOriginalPath(url);
                media.setPosition(i);
                media.setLat(imageBean.getLat());
                media.setLon(imageBean.getLon());
                media.setLocationInfo(imageBean.getLocationInfo());
                media.setData(imageBean.getDate());
                if (!TextUtils.isEmpty(SharedPrefHelper.getInstance().getUserNickName())) {
                    media.setUser(SharedPrefHelper.getInstance().getUserNickName());
                } else {
                    media.setUser("核查员");
                }
                selectList.add(media);
            }
            PictureSelector.create(activity)
                    .themeStyle(R.style.picture_default_style) // xml设置主题
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .isNotPreviewDownload(false)// 预览图片长按是否可以下载
                    .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .openExternalPreview(position, selectList);
        }else if(CaFile.type_video.equals(image.getImgType())){
            LocalMedia media = new LocalMedia();
            String url = image.getLocalPath();
            if(TextUtils.isEmpty(url)){
                url = BuildConfig.BASEFILEURL+image.getFileId()
                        +"?token="+ SharedPrefHelper.getInstance().getToken();
            }
            media.setPath(url);
            media.setRealPath(url);
            media.setCutPath(url);
            media.setAndroidQToPath(url);
            media.setCompressPath(url);
            media.setOriginalPath(url);
            PictureSelector.create(activity)
                    .themeStyle(R.style.picture_default_style)
                    .externalPictureVideo(TextUtils.isEmpty(media.getAndroidQToPath()) ?
                            media.getPath() : media.getAndroidQToPath());
        }else if(CaFile.type_audio.equals(image.getImgType())){
            LocalMedia media = new LocalMedia();
            String url = image.getLocalPath();
            if(TextUtils.isEmpty(url)){
                url = BuildConfig.BASEFILEURL+image.getFileId()
                        +"?token="+ SharedPrefHelper.getInstance().getToken();
            }
            media.setPath(url);
            media.setRealPath(url);
            media.setCutPath(url);
            media.setAndroidQToPath(url);
            media.setCompressPath(url);
            media.setOriginalPath(url);
//                                PictureSelector.create(getActivity())
//                                        .externalPictureAudio(PictureMimeType.isContent(media.getPath()) ? media.getAndroidQToPath() : media.getPath());
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mime = mimeTypeMap.getMimeTypeFromExtension(FileUtils.
                    getFileEndName(url));
            File file = new File(url);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile((activity),
                        context.getApplicationContext().getPackageName() + ".fileprovider", file);
            } else {
                uri = Uri.fromFile(file);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, mime);
            (activity).startActivity(intent);
        }
    }

    @Override
    public void selectPhoto(CaFile image) {
        if(image==null)return;
        //0 照片 1 音频  2 视频
        SharedPrefHelper.getInstance().setCurrentPhotoVideoAudioFor(currentLevel.getDictName());
        if(CaFile.type_image.equals(image.getImgType())){
            takeImageViewListener.takePhoto(taskProject);
        }else if(CaFile.type_video.equals(image.getImgType())){
            takeImageViewListener.takeVideo(taskProject);
        }else if(CaFile.type_audio.equals(image.getImgType())){
            takeImageViewListener.takeAudio(taskProject);
        }
    }

    public void addData(CaFile imageBean) {
        photos.add(0,imageBean);
        photoAdapter.notifyDataSetChanged();
    }

    public interface TakeImageDeleteListener{
        void deleteSuccess();
        void deleteError();
    }
    //
    public interface TakeImageViewListener{
        void takePhoto(TaskProject taskProject);
        void takeVideo(TaskProject taskProject);
        void takeAudio(TaskProject taskProject);
        void deleteFileOnline(TaskProject taskProject,CaData caData,String fileId,TakeImageDeleteListener listener);
    }
    private TakeImageViewListener takeImageViewListener;

    public void setHcCreateViewListener(TakeImageViewListener takeImageViewListener) {
        this.takeImageViewListener = takeImageViewListener;
    }


    @Override
    public void onItemDelete(int position, CaFile image) {
        if(image==null)return;
        //0 照片 1 音频  2 视频
        String promote = "";
        if(CaFile.type_image.equals(image.getImgType())){
            promote = "是否删除当前图片";

        }else if(CaFile.type_video.equals(image.getImgType())){
            promote = "是否删除当前视频";
        }else if(CaFile.type_audio.equals(image.getImgType())){
            promote = "是否删除当前音频";
        }
        DialogUtils.showPromote2(context, promote, null, new DialogUtils.OnConfirmListener() {
            @Override
            public void onConfirmed() {
                if(TextUtils.isEmpty(image.getFileId())){
                    CaFile item = photos.remove(position);
                    photoAdapter.notifyDataSetChanged();
                    //删除文件
                    File file = new File(item.getLocalPath());
                    if(file.exists()){
                        file.delete();
                    }
                }else {
                    takeImageViewListener.deleteFileOnline(taskProject, data,
                            image.getFileId(), new TakeImageDeleteListener() {
                                @Override
                                public void deleteSuccess() {
                                    CaFile item = photos.remove(position);
                                    photoAdapter.notifyDataSetChanged();
                                }

                                @Override
                                public void deleteError() {
                                    ToastUtils.toast("删除失败");
                                }
                            });
                }
            }
        });
    }
}
